﻿import sqlite3
import tkinter as tk
from tkinter import ttk, messagebox, filedialog

# 原始数据（示例部分，需补充完整）
data = [
    [29, 49, 48, 30, 41, 36, 14],
    # ...（这里需要包含完整的169组数据）...
]

DB_NAME = 'lottery.db'

class LotteryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("彩票数据管理系统")
        self.root.geometry("1000x700")
        
        # 初始化数据库
        self.init_db()
        
        # 创建界面
        self.create_widgets()
        self.load_data()

    def init_db(self):
        self.conn = sqlite3.connect(DB_NAME)
        self.c = self.conn.cursor()
        
        # 创建表
        self.c.execute('''
            CREATE TABLE IF NOT EXISTS groups (
                id INTEGER PRIMARY KEY,
                n1 INTEGER, n2 INTEGER, n3 INTEGER,
                n4 INTEGER, n5 INTEGER, n6 INTEGER,
                n7 INTEGER
            )
        ''')
        
        # 检查并导入初始数据
        self.c.execute('SELECT COUNT(*) FROM groups')
        if self.c.fetchone()[0] == 0:
            self.import_initial_data()
        self.conn.commit()

    def import_initial_data(self):
        for idx, group in enumerate(data):
            group_id = idx + 1
            self.c.execute('''
                INSERT INTO groups 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ''', (group_id, *group))
        self.conn.commit()

    def create_widgets(self):
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 左侧控制面板
        control_frame = ttk.LabelFrame(main_frame, text="操作面板")
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)

        # 生成参数设置
        ttk.Label(control_frame, text="倍数（逗号分隔）:").pack(anchor=tk.W)
        self.multiplier_entry = ttk.Entry(control_frame, width=15)
        self.multiplier_entry.pack(pady=5)
        self.multiplier_entry.insert(0, "4,5,6")

        ttk.Label(control_frame, text="最大n值:").pack(anchor=tk.W)
        self.n_max_entry = ttk.Entry(control_frame, width=15)
        self.n_max_entry.pack(pady=5)
        self.n_max_entry.insert(0, "13")

        ttk.Button(control_frame, text="生成数据", 
                  command=self.generate_data).pack(pady=10)

        ttk.Separator(control_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 新增删除按钮
        ttk.Button(control_frame, text="删除选中数据", 
                  command=self.delete_selected_data, 
                  style="Delete.TButton").pack(pady=5)

        # 新增批量导入按钮
        ttk.Button(control_frame, text="批量导入数据", 
                  command=self.import_batch_data).pack(pady=5)

        ttk.Separator(control_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 添加数据按钮
        ttk.Button(control_frame, text="添加新数据", 
                  command=self.add_data_dialog).pack(pady=5)

        # 数据表格
        self.tree_frame = ttk.Frame(main_frame)
        self.tree_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

        # 表格和滚动条
        self.tree = ttk.Treeview(self.tree_frame, 
                               columns=('ID', 'Numbers'), 
                               show='headings')
        vsb = ttk.Scrollbar(self.tree_frame, 
                           orient="vertical", 
                           command=self.tree.yview)
        hsb = ttk.Scrollbar(self.tree_frame,
                           orient="horizontal",
                           command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        self.tree.heading('ID', text='组号')
        self.tree.heading('Numbers', text='号码')
        self.tree.column('ID', width=80, anchor=tk.CENTER)
        self.tree.column('Numbers', width=400, anchor=tk.W)

        # 绑定右键删除
        self.tree.bind('<Button-3>', self.show_context_menu)

        # 布局
        self.tree.grid(row=0, column=0, sticky='nsew')
        vsb.grid(row=0, column=1, sticky='ns')
        hsb.grid(row=1, column=0, sticky='ew')
        self.tree_frame.grid_rowconfigure(0, weight=1)
        self.tree_frame.grid_columnconfigure(0, weight=1)

    def load_data(self):
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        self.c.execute('SELECT * FROM groups ORDER BY id')
        for row in self.c.fetchall():
            group_id = row[0]
            numbers = f"{row[1]:02d} {row[2]:02d} {row[3]:02d} " \
                     f"{row[4]:02d} {row[5]:02d} {row[6]:02d} {row[7]:02d}"
            self.tree.insert('', tk.END, values=(group_id, numbers))

    def generate_data(self):
        try:
            multipliers = list(map(int, self.multiplier_entry.get().split(',')))
            n_max = int(self.n_max_entry.get())
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字")
            return

        result_window = tk.Toplevel(self.root)
        result_window.title("生成结果")
        
        text_area = tk.Text(result_window, wrap=tk.WORD)
        vsb = ttk.Scrollbar(result_window, command=text_area.yview)
        text_area.configure(yscrollcommand=vsb.set)
        
        vsb.pack(side=tk.RIGHT, fill=tk.Y)
        text_area.pack(fill=tk.BOTH, expand=True)

        for m in multipliers:
            text_area.insert(tk.END, f"\n### {m}×n（n=1-{n_max}）\n")
            for n in range(1, n_max+1):
                group_id = m * n
                self.c.execute('SELECT * FROM groups WHERE id = ?', (group_id,))
                row = self.c.fetchone()
                if row:
                    numbers = f"{row[1]:02d} {row[2]:02d} {row[3]:02d} " \
                            f"{row[4]:02d} {row[5]:02d} {row[6]:02d} {row[7]:02d}"
                    text_area.insert(tk.END, f"{numbers}\n")

    def add_data_dialog(self):
        dialog = tk.Toplevel(self.root)
        dialog.title("添加新数据")
        
        entries = []
        ttk.Label(dialog, text="组号:").grid(row=0, column=0, padx=5, pady=2)
        group_entry = ttk.Entry(dialog)
        group_entry.grid(row=0, column=1, padx=5, pady=2)
        
        for i in range(7):
            ttk.Label(dialog, text=f"号码{i+1}:").grid(row=i+1, column=0, padx=5, pady=2)
            entry = ttk.Entry(dialog)
            entry.grid(row=i+1, column=1, padx=5, pady=2)
            entries.append(entry)
        
        def save_data():
            try:
                group_id = int(group_entry.get())
                if group_id <= 0:
                    raise ValueError("组号必须为正整数")
                numbers = [int(entry.get()) for entry in entries]
                if len(numbers) != 7:
                    raise ValueError("需要输入7个号码")
                if any(not (1 <= num <= 49) for num in numbers):
                    raise ValueError("号码必须为1-49之间的整数")
            except ValueError as e:
                messagebox.showerror("输入错误", str(e))
                return

            # 开始事务处理
            self.conn.execute('BEGIN TRANSACTION')
            try:
                # 获取需要更新的记录（降序排列）
                self.c.execute('''
                    SELECT id FROM groups 
                    WHERE id >= ? 
                    ORDER BY id DESC
                ''', (group_id,))
                rows = self.c.fetchall()
                
                # 逐个更新记录
                for row in rows:
                    current_id = row[0]
                    self.c.execute('''
                        UPDATE groups 
                        SET id = ? 
                        WHERE id = ?
                    ''', (current_id + 1, current_id))
                
                # 插入新数据
                self.c.execute('''
                    INSERT INTO groups 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ''', (group_id, *numbers))
                
                self.conn.commit()
                self.load_data()
                dialog.destroy()
                messagebox.showinfo("成功", "数据已保存")
            except sqlite3.IntegrityError as e:
                self.conn.rollback()
                messagebox.showerror("数据库错误", f"主键冲突：{str(e)}")
            except Exception as e:
                self.conn.rollback()
                messagebox.showerror("错误", f"保存数据时发生错误：{str(e)}")

        ttk.Button(dialog, text="保存", command=save_data).grid(row=8, columnspan=2, pady=10)

    def delete_selected_data(self):
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请选择要删除的数据")
            return

        confirm = messagebox.askyesno("确认删除", "确定要删除选中的数据吗？")
        if not confirm:
            return

        # 开始事务处理
        self.conn.execute('BEGIN TRANSACTION')
        try:
            for item in selected_item:
                group_id = int(self.tree.item(item, "values")[0])
                
                # 删除数据
                self.c.execute('DELETE FROM groups WHERE id = ?', (group_id,))
                
                # 获取需要更新的记录（升序排列）
                self.c.execute('''
                    SELECT id FROM groups 
                    WHERE id > ? 
                    ORDER BY id ASC
                ''', (group_id,))
                rows = self.c.fetchall()
                
                # 逐个更新记录
                for row in rows:
                    current_id = row[0]
                    self.c.execute('''
                        UPDATE groups 
                        SET id = ? 
                        WHERE id = ?
                    ''', (current_id - 1, current_id))
            
            self.conn.commit()
            self.load_data()
            messagebox.showinfo("成功", "数据已删除")
        except Exception as e:
            self.conn.rollback()
            messagebox.showerror("错误", f"删除数据时发生错误：{str(e)}")

    def import_batch_data(self):
        file_path = filedialog.askopenfilename(
            title="选择数据文件",
            filetypes=(("文本文件", "*.txt"), ("CSV文件", "*.csv"), ("所有文件", "*.*"))
        )
        if not file_path:
            return

        try:
            with open(file_path, 'r') as f:
                lines = f.readlines()
        except Exception as e:
            messagebox.showerror("错误", f"无法读取文件：{str(e)}")
            return

        valid_count = 0
        error_count = 0

        # 开始事务处理
        self.conn.execute('BEGIN TRANSACTION')
        try:
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                parts = line.split()
                if len(parts) != 8:
                    error_count += 1
                    continue

                try:
                    group_id = int(parts[0])
                    numbers = list(map(int, parts[1:8]))
                    if any(not (1 <= num <= 49) for num in numbers):
                        raise ValueError
                except (ValueError, IndexError):
                    error_count += 1
                    continue

                # 处理组号冲突
                self.c.execute('''
                    SELECT id FROM groups 
                    WHERE id >= ? 
                    ORDER BY id DESC
                ''', (group_id,))
                rows = self.c.fetchall()
                
                for row in rows:
                    current_id = row[0]
                    self.c.execute('''
                        UPDATE groups 
                        SET id = ? 
                        WHERE id = ?
                    ''', (current_id + 1, current_id))
                
                self.c.execute('''
                    INSERT INTO groups 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ''', (group_id, *numbers))
                valid_count += 1

            self.conn.commit()
            self.load_data()
            messagebox.showinfo("导入完成", 
                f"成功导入{valid_count}条数据，失败{error_count}条")
        except Exception as e:
            self.conn.rollback()
            messagebox.showerror("导入错误", f"导入过程中发生错误：{str(e)}")

    def show_context_menu(self, event):
        selected_item = self.tree.identify_row(event.y)
        if selected_item:
            self.tree.selection_set(selected_item)
            menu = tk.Menu(self.root, tearoff=0)
            menu.add_command(label="删除", command=self.delete_selected_data)
            menu.post(event.x_root, event.y_root)

if __name__ == '__main__':
    root = tk.Tk()
    style = ttk.Style()
    style.configure("Delete.TButton", foreground="red")
    app = LotteryApp(root)
    root.mainloop()